import { db, initSqlite, close as closeSqlite, create, insert, get, search } from './sqlite3/index'
import { app } from 'electron'
import path from 'path'

// 初始化数据库
export const initDatabase = () => {
  // 连接sqlite
  initSqlite()
}

// 关闭数据库
export const closeDatabase = () => {
  // 关闭sqlite
  closeSqlite()
}

//创建表
export const createTableMessage = () => {
  create()
}

//插入数据
export const insertMessage = insertData => {
  insert(insertData)
}

// 分页获取数据
export const getMessagesByPage = (page, pageSize, chatId) => {
  return new Promise((resolve, reject) => {
    get(page, pageSize, chatId)
      .then(data => {
        resolve(data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

//模拟搜索
export const searchWholeMessagesLike = searchText => {
  return new Promise((resolve, reject) => {
    search(searchText)
      .then(res => {
        resolve(res)
      })
      .catch(err => {
        reject(err)
      })
  })
}

//更新消息某项数据
export const updateMessage = (id, key, fileName) => {
  db.run(`UPDATE messages SET ${key} =? WHERE id =?`, path.join(app.getPath('userData'), `/file/${fileName}`), id, function (err) {
    if (err) {
      console.log(err)
    } else {
      console.log(`更新成功1111`)
    }
  })
}
